package com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.dao;

import com.skytech.tax.customsdatawarehouse.singlewindow.customsdeclarations.domain.entity.IECustomsDeclaration;
import com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.entity.TaxBillGoods;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Lianhong
 * @since 2022/4/19
 */
@Repository
public class TaxBillGoodsDao {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;


    private String deleteTaxBillGoodsSql = "DELETE FROM sw_tax_bill_goods WHERE taxHeadSeqNo = :taxHeadSeqNo";

    public void deleteBy(String taxHeadSeqNo) {
        Map<String, Object> params = new HashMap<>();
        params.put("taxHeadSeqNo", taxHeadSeqNo);
        namedParameterJdbcTemplate.update(this.deleteTaxBillGoodsSql, params);
    }

    private String insertTaxBillGoodsSql = "INSERT INTO sw_tax_bill_goods (taxHeadSeqNo, taxBillGoods, socialCreditCode, storageTime) " +
            "VALUES (:taxHeadSeqNo, :taxBillGoods, :socialCreditCode, :storageTime)";

    public void save(TaxBillGoods goods) {
        this.namedParameterJdbcTemplate.update(this.insertTaxBillGoodsSql, new BeanPropertySqlParameterSource(goods));
    }

    private String existsCustomsDeclarationSimpleSql = "SELECT count(1) FROM sw_tax_bill_goods WHERE taxHeadSeqNo = ?";

    public boolean exists(String taxHeadSeqNo) {
        Integer count = namedParameterJdbcTemplate.getJdbcOperations()
                .queryForObject(this.existsCustomsDeclarationSimpleSql, new Object[]{taxHeadSeqNo}, Integer.class);
        return count != null && count > 0;
    }

    private String selectTaxBillGoodsSql = "SELECT taxHeadSeqNo, taxBillGoods, socialCreditCode, storageTime FROM sw_tax_bill_goods WHERE taxHeadSeqNo=:taxHeadSeqNo";

    public TaxBillGoods findBy(String taxHeadSeqNo) {
        Map<String, Object> params = new HashMap<>();
        params.put("taxHeadSeqNo", taxHeadSeqNo);
        return namedParameterJdbcTemplate.queryForObject(selectTaxBillGoodsSql, params, new BeanPropertyRowMapper<>(TaxBillGoods.class));
    }
}
